/**
 * JS文本标签
 * @time 2014-4-10
 * @author tugenhua
 */
function AddTag(options) {

    this.config = {
        labelDiv      :  '.labels-div',            // 放置label的div
        labelInput    :  '.mb-input',              // 输入label的input
        hiddenInput   :  '#patient-pt_label',      // 放置label id的input
        labels        :  [],                       // 数据库中的label
        label_ids     :  [],                       // 数据库中的label.id
    };

    this.cache = {
        arrs :  []
    };

    this.init(options);
}
AddTag.prototype = {

    constructor: AddTag,
    init: function(options){
        this.config = $.extend(this.config,options || {});
        var self = this,
            _config = self.config,
            _cache = self.cache;

        self._bindEnv();
        self.initInput();
        self.initLabel();
    },
    /*
     * 绑定事件
     * @method _bindEnv
     * keycode 13->enter键
     */
    _bindEnv: function(){
        var self = this,
            _config = self.config,
            _cache = self.cache;
        // input enter键 事件
        $(_config.labelInput).unbind('keyup keypress').bind('keypress',function(e){

            var keyCode = e.keyCode,
                curValue = $.trim($(this).val());
            if(keyCode == 13) {
                self._renderHTML(curValue, true);
                return false;
            }

            self.suggest();
        });
    },
    /*
     * 添加html标签
     * @method _renderHTML
     * @param {curValue} 当前值
     */
    _renderHTML: function(curValue, isNeedSave){
        if (curValue == '') {
            layer.msg('添加标签不能为空');
            return false;
        }

        var self = this,
            _config = self.config,
            _cache = self.cache;

        var html = '<div class="label label-info">' + curValue + ' <i class="fa fa-times"></i></div>';

        if($('div', _config.labelDiv).length > 0) {
            $('div', _config.labelDiv).each(function(){
                var dataTag = $(this).html().match(/^(.+) </)[1];
                _cache.arrs.push(dataTag);
                _cache.arrs = self.unique(_cache.arrs);
            });
        }
        var curIndex = self._indexOf(curValue,_cache.arrs);
        if(curIndex < 0) {
            if (isNeedSave) self.save(curValue);
            $(_config.hiddenInput).before(html);
            $(_config.labelInput).val('');
        }else {
            layer.alert('重复项,请重新输入');
            $(_config.labelInput).focus();
            return true;
        }
        
        //  关闭事件
        self._closedEnv();
    },
    
    /*
     * 设置隐藏input的值
     * @method setHidden
     * @param (value, type, isNeedSetInput) [1=>标签id值, 2=>label-div], [1=>set, 2=>remove]
     */
    setHidden: function(value, type, isNeedSetInput) {
        var self = this,
            _config = self.config,
            hidden = $(_config.hiddenInput).val();

        if (type == 1) {
            var _value = hidden + ((hidden != '') ? '+' : '') + value,
                labels = $(_config.hiddenInput).siblings("div"),
                last_label = labels[labels.length - 1];

            if (isNeedSetInput) $(_config.hiddenInput).val(_value);
            $(last_label).attr('data-tag', value);

        } else {
            var _value = $(value).attr('data-tag'),
                str_pattern = '([^0-9]+|^)' + _value + '([^0-9]+|$)',
                pattern = new RegExp(str_pattern),
                after = hidden.replace(pattern, '+');

            $(_config.hiddenInput).val(after);
        }
    },
    /*
     * 关闭事件
     */
    _closedEnv: function() {
        var self = this,
            _config = self.config,
            _cache = self.cache;

        // 关闭X按钮事件
        if($('i', _config.labelDiv).length > 0) {
            $('i', _config.labelDiv).each(function(){
                $(this).unbind('click').bind('click',function(){
                    var liparent = $(this).closest('div'),
                        tagVal = $.trim($(liparent).html().match(/^(.+) </)[1]);

                    self.setHidden(liparent, 2, true);
                    self._removeItem(tagVal, _cache.arrs);
                    _cache.arrs = self.unique(_cache.arrs);

                    $(liparent).remove();
                });
            });
        }
    },
    /*
     * 从数组里面删除一项
     * @method _removeItem
     * @param {item,arr} 当前的项 数组
     * @return 返回新数组
     */
    _removeItem: function(item,arr){
        var self = this,
            index = self._indexOf(item,arr);
        if(index > -1) {
            arr.splice(index, 1);
        }
    },
    /*
     * 索引 jquery1.8 indexof 会重新排序 所以没有用jquery indexof
     */
    _indexOf: function(item,arr) {
        if(Array.prototype.indexOf) {
            return arr.indexOf(item);
        }else {
            for(var i = 0, ilen = arr.length; i < ilen; i+=1) {
                if(arr[i] == item) {
                    return i;
                }else {
                    return -1;
                }
            }
        }
    },
    /*
     * 去掉数组重复项
     * @method unique
     * @param array
     * @return newArray
     */
    unique: function(arr){
        arr = arr || [];
        var obj = {},
            ret = [];
        for(var i = 0, ilen = arr.length; i < ilen; i+=1) {
            var curItem = arr[i],
                curItemType = typeof(curItem) + curItem;
            if(obj[curItemType] !== 1) {
                ret.push(curItem);
                obj[curItemType] = 1;
            }
        }
        return ret;
    },
    initInput: function() {
        var self = this,
            _config = self.config;

        $.ajax({
            type: 'post',
            url: '/label/view',
            data: 'pt_label=' + $(_config.hiddenInput).val(),
            success: function(data) {
                for (var i = 0; i < data.length; i ++) {
                    self._renderHTML(data[i].name, false);
                    self.setHidden(data[i].id, 1, false);
                }
            }
        });
    },
    initLabel: function() {
        var self = this,
            _config = self.config;

        $.ajax({
            type: 'get',
            url: '/label/get-all',
            success: function(data) {
                for (var i = 0; i < data.length; i ++) {
                    _config.labels.push(data[i].name);
                }
                self.suggest();
            }
        });
    },
    /*
     * 检查标签
     * @method save
     * @param name 标签名称
     */
    save: function(name) {
        var self = this;
        
        $.ajax({
            type: 'post',
            url: '/label/create',
            data: 'name=' + name,
            success: function(data) {
                if (data.code != 200) {
                    layer.msg(data.msg);
                } else {
                    self.setHidden(data.msg, 1, true);
                }
            }
        });
    },
    /*
     * 下拉提示框
     * @method suggest
     */
    suggest: function() {
        var self = this,
            _config = self.config;

        $(_config.labelInput).autocomplete({
            source: _config.labels
        });
    },
};